/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.controller;

import cn.easyplatform.lang.Files;
import cn.easyplatform.lang.Streams;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.response.LoginResponseMessage;
import cn.easyplatform.messages.vos.AuthorizationVo;
import cn.easyplatform.messages.vos.EnvVo;
import cn.easyplatform.messages.vos.LoginVo;
import cn.easyplatform.messages.vos.OrgVo;
import cn.easyplatform.spi.service.IdentityService;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.type.UserType;
import cn.easyplatform.web.contexts.Contexts;
import cn.easyplatform.web.service.ServiceLocator;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.InputEvent;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.*;
import org.zkoss.zul.Timer;

import java.util.*;
import java.util.HashMap;
import java.util.List;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class PhoneCheckController extends SelectorComposer<Window> {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Wire("label#phone")
    private Label phone;

    @Wire("textbox#checkCode")
    private Textbox checkCode;

    @Wire("label#countdown")
    private Label countdown;

    @Wire("button#send")
    private Button send;

    @Wire("button#ok")
    private Button ok;

    @Wire("timer#timer")
    private Timer timer;

    private int count = 60;

    private EnvVo env;

    private LoginVo vo;

    @Override
    public void doAfterCompose(Window comp) throws Exception {
        super.doAfterCompose(comp);
        phone.setValue((String) Executions.getCurrent().getArg().get("phone"));
        vo = (LoginVo) Executions.getCurrent().getArg().get("vo");
        env = (EnvVo) Executions.getCurrent().getArg().get("env");
        ok.setDisabled(true);
        checkCode.setReadonly(true);
        countdown.setValue("60" + Labels.getLabel("admin.jvm.second"));
    }

    @Listen("onClick=#send")
    public void send() {
        IdentityService uc = ServiceLocator
                .lookup(IdentityService.class);
        IResponseMessage<?> resp = uc.callback(new SimpleRequestMessage());
        if (resp.isSuccess()) {
            timer.setRunning(true);
            send.setDisabled(true);
            checkCode.setReadonly(false);
        } else
            Clients.wrongValue(send, (String) resp.getBody());
    }

    @Listen("onChange=#checkCode")
    public void onChanged(InputEvent event) {
        ok.setDisabled(Strings.isBlank(event.getValue()));
    }

    @Listen("onClick=#ok;onOK=window")
    public void submit() {
        if (Strings.isBlank(checkCode.getValue()))
            return;
        IdentityService uc = ServiceLocator
                .lookup(IdentityService.class);
        IResponseMessage<?> rp = uc.callback(new SimpleRequestMessage(checkCode.getValue()));
        if (rp.isSuccess()) {
            Session session = ok.getDesktop().getSession();
            LoginResponseMessage resp = (LoginResponseMessage) rp;
            vo.setType(resp.getType());
            vo.setTooltip(resp.getTooltip());
            vo.setName(resp.getName());
            if (resp.getBody() instanceof List<?>) {
                Map<String, Object> args = new HashMap<String, Object>(1);
                args.put("orgs", resp.getBody());
                args.put("vo", vo);
                Executions.createComponents("~./pages/org.zul", null, args);
                this.getSelf().detach();
            } else if (resp.getBody() instanceof AuthorizationVo) {
                vo.setOrgId(resp.getOrgId());
                AuthorizationVo av = (AuthorizationVo) resp.getBody();
                if (vo.getType() == UserType.TYPE_ADMIN)
                    env.setMainPage(Streams.readAndClose(Streams.utf8r(Files
                            .findFileAsStream("web/admin/admin.zul"))));
                else
                    env.setMainPage(av.getMainPage());
                session.setAttribute(Contexts.PLATFORM_USER, vo);
                session.setAttribute(Contexts.PLATFORM_APP_ENV, env);
                session.setAttribute(Contexts.PLATFORM_USER_AUTHORIZATION, av);
                Executions.sendRedirect("/main.go");
            }
        } else
            Clients.wrongValue(ok, (String) rp.getBody());
    }

    @Listen("onClick=#cancel;onCancel=window")
    public void cancel(Event event) {
        IdentityService uc = ServiceLocator
                .lookup(IdentityService.class);
        uc.logout(new SimpleRequestMessage());
        IResponseMessage<?> resp = uc.getAppEnv(new SimpleRequestMessage(env));
        if (resp.isSuccess()) {
            env = (EnvVo) resp.getBody();
            Sessions.getCurrent().removeAttribute(Contexts.PLATFORM_USER);
            Sessions.getCurrent().setAttribute(Constants.SESSION_ID, env.getSessionId());
            Sessions.getCurrent().setAttribute(Contexts.PLATFORM_APP_ENV, env);
            this.getSelf().detach();
        } else
            Clients.wrongValue(event.getTarget(), (String) resp.getBody());

    }

    @Listen("onTimer=#timer")
    public void onEvent() {
        if (count == 0) {
            ok.setDisabled(true);
            checkCode.setReadonly(true);
            timer.setRunning(false);
            send.setDisabled(false);
            checkCode.setValue("");
            count = 60;
        } else {
            count--;
        }
        countdown.setValue(count + Labels.getLabel("admin.jvm.second"));
    }
}
